package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.service.ApUserFanService;
import com.usian.user.service.ApUserFollowService;
import com.usian.user.service.ApUserService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import jdk.management.resource.internal.ApproverGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Auther:ASS
 * @Date:2023/3/1 16:45
 */
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private ApUserFanService apUserFanService;
    @Autowired
    private ApUserService apUserService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 关注或取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {


        //1：判断参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //2:远程调用查作者的信息名称
        ApAuthor apAuthor = apAuthorFeign.findById(dto.getAuthorId());
        if (apAuthor != null) {
            //3：看关注：0还是取消关注：1

            ApUser apUser = AppThreadLocalUtils.getUser();

            Integer userId = null;
            if (apUser != null) {
                userId = apUser.getId();
            }
            //如果传过来的参数 调定义的方法
            if (dto.getOperation() == 0) {
                //关注
                boolean resule = follows(userId, dto.getAuthorId(), apAuthor.getName(),dto.getArticleId());
                if (!resule) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
                }
            } else if (dto.getOperation() == 1) {

                //取消关注
                cancelFollows(userId, dto.getAuthorId(), apAuthor.getName());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //取消关注

    public void cancelFollows(Integer userId, Integer followId, String followName) {
        //先删follow
        this.remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, followId));


        //在删userfan表
        apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, userId));
    }

    //定义一个关注的方法
    public boolean follows(Integer userId, Integer followId, String followName,Long articleId) {

        boolean flag = true;

        //保存之前查询一下看看有没有数据
        ApUserFollow userFollow = this.getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, followId));

        if (userFollow == null) {
            //如果是空的就记录一下子
            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(userId);
            apUserFollow.setFollowId(followId);
            apUserFollow.setFollowName(followName);
            apUserFollow.setLevel((short) 1);
            apUserFollow.setIsNotice(true);
            apUserFollow.setCreatedTime(new Date());
            this.save(apUserFollow);

            //在保存 Fan表
            ApUserFan apUserFan = apUserFanService.getOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, userId));

            //先保存 follow表 保存两张表的数据

            if (apUserFan == null) {
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(userId.longValue());

                ApUser apUser = apUserService.getById(userId);
                if (apUser != null) {
                    apUserFan.setFansName(apUser.getName());
                }
                apUserFan.setLevel((short) 0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanService.save(apUserFan);
            }


            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setUserId(userId);
            dto.setFollowId(followId);
            dto.setArticleId(articleId);
            kafkaTemplate.send("followBehavior", JSON.toJSONString(dto));
            System.out.println("用户关注行为发送信息"+JSON.toJSONString(dto));
        } else {
            flag = false;
        }
        return flag;
    }
}

